<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Order extends MY_Controller {

	function buy_now(){
		$post_data = $this->input->post();
		$this->load->model('Order_model');
		$settle_id = $this->Order_model->buy_now($this->user_data['id'],$post_data['course_id'],$post_data['num']);
		if($settle_id>0){
			header("Location:/order/settle/{$settle_id}");exit;
		}
	}
	/**
	 * 结算预览页面
	 *
	 */
	public function settle($id)
	{
    if( $this->logged_in==0) {header("Location:/");exit;}
    	
		$post_data = $this->input->post();
		$this->load->model('Order_model');
		//查询结算信息
		$settle = $this->Order_model->get_settle_by_id($id);
		$course_type = $settle['order_type'];
		if(empty($settle)) {header("Location:/");exit;}

		if($course_type == 1){
			$this->check_school_video_user_code();
		}
		if($post_data){
			$has_err = 0;
			//判断学员信息是否完善
			if($course_type == 3){
				$this->load->model('Student_model');
				$student = $this->Student_model->get_student_by_userid($this->user_data['id']);
				if(empty($student)){
					$this->smarty->assign("error", "请填写学员信息");
					$has_err = 1;
				}
			}
			if($has_err == 0){

				$this->load->model('Order_model');
				if($course_type == 4){
					$order_id = $this->Order_model->submit_subject_order($post_data['settle_id']);
				}else{
					$order_id = $this->Order_model->submit_order($post_data['settle_id'],$course_type);
				}

			    if($order_id>0){
			      header("Location:/order/pay/{$order_id}");exit;
			    }
			}
		}




		//查询购物车信息
    	$cart_list = $this->Order_model->get_cart_info_by_settle($id, $course_type);
		if(empty($cart_list)){header("Location:/");exit;}
    	// print_r($cart_list);exit;
		$this->smarty->assign("cart_list", $cart_list);
	    //计算总价
	    $total_amout = 0.0;
	    foreach ($cart_list as $cart) {
	      $total_amout += $cart['price'] * $cart['quantity'];
	    }
	    $this->smarty->assign("total_amout", $total_amout);

		//获取学员信息
		$this->load->model('Student_model');
		$student = $this->Student_model->get_student_by_userid($this->user_data['id']);
	  	$this->smarty->assign("student", $student);
	  	$this->smarty->assign("course_type", $course_type);
	    $this->smarty->assign("settle_id", $id);
		$this->smarty->display("order/settle.html");
	}

	/**
	 * 设置学员信息
	 * @param  string $value [description]
	 * @return [type]        [description]
	 */
	public function student_info()
	{
		// $settle_id = $this->input->get('settle_id');
		// $this->smarty->assign("settle_id", $settle_id);
		$post_data = $this->input->post();

		if($post_data){
			$this->load->model('Student_model');
			$result = $this->Student_model->add_student_info($this->user_data['id'],$post_data);
			if($result>0){
				print_r('{"result":"0","msg":"success"}');exit;
				// $this->smarty->display("order/student_info_success.html");
				// exit;
	    	}
		}
		$this->load->model('Student_model');
		$student = $this->Student_model->get_student_by_userid($this->user_data['id']);
  		$this->smarty->assign("student", $student);
		$this->smarty->display("order/student_info.html");

	}



  /**
  **  订单支付
  */
  function pay($order_id){
    $this->load->model('Order_model');
    $order = $this->Order_model->get_order_by_id($order_id);
	if(empty($order)){
		header("Location:/");exit;
	}
	if($this->logged_in==0){
		header("Location:/logreg");exit;
	}
	if($order['order_type'] == 1){
		$this->check_school_video_user_code();
	}
	// print_r($this->user_data['id']);exit;
	if($order['buyer_user_id']!=$this->user_data['id']){
		print_r("不是你的订单");
		exit;
	}

	//调取微信支付统一下单接口
	$response = self::create_wx_order($order);
	// print_r($response);
	$this->smarty->assign("data", $response);

    $this->smarty->assign("order", $order);

    $this->smarty->display("order/pay.html");
  }

  function create_wx_order($order_info){
  	require_once 'third_party/wxpayApi/wxpay.php';
    $wx_config_data = get_field_by_where("o2o_school_wx_config", "*", "school_id='{$this->school_id}'");
    if(!$wx_config_data){
    	show_error("该学校尚不支持微信支付");exit;
    }
    $wx_config['appid'] = $wx_config_data['app_id'];
    $wx_config['mch_id'] = $wx_config_data['mch_id'];
    $wx_config['apikey'] = $wx_config_data['apikey'];
    $wx_config['sslcertPath'] = $wx_config_data['apiclient_cert'];
    $wx_config['sslkeyPath'] = $wx_config_data['apiclient_key'];
    $wx_config['notify_url'] = $this->config->item("wx_pay_notify_url");

    $products = json_decode($order_info['order_products'],true);
    $products_id = '';
    $products_name = '';
    $price = 0;//$order_info['payment_money_amount'];

    foreach ($products as $key => $value) {
    	if($key != 0){
    		$products_id .= ',' . $value['id'];
    		$products_name .= "、" . $value['title'];
    	}else{
    		$products_id .= $value['id'];
    		$products_name .= $value['title'];
    	}
    	// $price += $value['price'];
    }
		$price = $order_info['payment_money_amount'];
		// print_r($price);exit;

    $weixin_pay = new wxpay($wx_config);
  	$param['body']             = "德安信订单-".$products_name;
    $param['attach']           = $order_info['order_id'];
    $param['detail']           = '德安信订单，单号：' . $order_info['order_id'];
    $param['out_trade_no']     = $order_info['order_id'];
    $param['total_fee']        = $price*100;
    $param["spbill_create_ip"] = $_SERVER['REMOTE_ADDR'];
    $param["time_start"]       = date("YmdHis");
    $param["time_expire"]      = date("YmdHis", time() + 50000);
    $param["notify_url"]       = $wx_config['notify_url'];
    $param["trade_type"]       = "JSAPI"; //扫码支付模式二
    $param["product_id"]       = $products_id;
    $openid = get_field_by_where("user", "open_id", "id='{$order_info['buyer_user_id']}'");
    $param['openid']		   = $openid['open_id'];

    //微信同一下单接口
    $response = $weixin_pay->unifiedOrder($param);
    /*var_dump($response);
    if(!$response || $response['return_code'] == 'FAIL'){
			show_error("微信统一下单失败，" . $response['return_msg']);exit;
		}*/

	if(isset($response['return_code']) && $response['return_code'] == 'SUCCESS'){
		if(isset($response['result_code']) && $response['result_code'] == 'SUCCESS'){
			
		}else{
			show_error($response['err_code_des']);exit;
		}
	}else{
		show_error("微信统一下单失败，" . $response['return_msg']);exit;
	}
		//更新prepay_id 到数据库
		$order_update_data = array(
			'payment_method' => 1,
			'payment_status' => 1,
			'payment_time'=>time(),
			'wx_prepay_id'=>$response['prepay_id']
		);
		$this->db->update('shopping_orders',$order_update_data, array('order_id' => $order_info['order_id'] ));
		$this->smarty->assign("wx_prepay_id", $response['prepay_id']);
    // var_dump($weixin_pay);exit;
    $response1 = $weixin_pay->get_package($response['prepay_id']);
    return $response1;
  }

  function test(){
  	require_once 'third_party/wxpayApi/wxpay.php';
    $this->config->load('wxpay', true);
    $wx_config  = $this->config->item('wxpay');
    $weixin_pay = new wxpay($wx_config);

    $response = $weixin_pay->orderQuery('', $order_no);

    $result = array('status' => -1, 'msg_code' => '', 'msg_des' => '', 'order' => '');
    if ($response['return_code'] == 'SUCCESS') {
        if ($response['result_code'] == 'SUCCESS') {
            $result['status'] = 0;
            $result['order']  = $response;
        } else {
            $result['status']   = 2;
            $result['msg_code'] = $response["err_code"];
            $result['msg_des']  = $response["err_code_des"];
        }
    } else {
        $result['status']   = 1;
        $result['msg_code'] = '微信服务器通信错误';
        $result['msg_des']  = $response["return_msg"];
    }

    exit(json_encode($result));
  }

	/**
	 * 支付成功跳转
	 * @param  [type] $order_id [description]
	 * @return [type]           [description]
	 */
	/*public function pay_success($order_id)
	{

		$this->load->model('Order_model');
    	$order = $this->Order_model->get_order_by_id($order_id);
		if(empty($order)){
			header("Location:/");exit;
		}
		if($this->logged_in==0){
			header("Location:/logreg");exit;
		}

		if($order['buyer_user_id']!=$this->user_data['id']){
			print_r("不是你的订单");
			exit;
		}
		//修改订单支付状态
		$this->Order_model->order_pay_success($order_id);

    	$this->smarty->assign("order", $order);

		$this->smarty->display("order/success.html");
	}*/

	public function pay_success($order_id)
	{

		/*$this->load->model('Order_model');
    	$order = $this->Order_model->get_order_by_id($order_id);
		if(empty($order)){
			header("Location:/");exit;
		}
		if($this->logged_in==0){
			header("Location:/logreg");exit;
		}

		if($order['buyer_user_id']!=$this->user_data['id']){
			print_r("不是你的订单");
			exit;
		}
		//修改订单支付状态
		$this->Order_model->order_pay_success($order_id);

    	$this->smarty->assign("order", $order);

		$this->smarty->display("order/success.html");*/

		$order_no = $order_id;
		require_once 'third_party/wxpayApi/wxpay.php';
		$wx_config_data = get_field_by_where("o2o_school_wx_config", "*", "school_id='{$this->school_id}'");
		if(!$wx_config_data || empty($wx_config_data['app_id']) || empty($wx_config_data['mch_id']) || empty($wx_config_data['apikey']) || empty($wx_config_data['apiclient_cert']) || empty($wx_config_data['apiclient_key'])){
			show_error_message("/user/orders", "该学校不支持微信支付");
		}
		$wx_config['appid'] = $wx_config_data['app_id'];
		$wx_config['mch_id'] = $wx_config_data['mch_id'];
		$wx_config['apikey'] = $wx_config_data['apikey'];
		$wx_config['sslcertPath'] = $wx_config_data['apiclient_cert'];
		$wx_config['sslkeyPath'] = $wx_config_data['apiclient_key'];
		$weixin_pay = new wxpay($wx_config);
		$response = $weixin_pay->orderQuery('', $order_no);
		$result = array('status' => -1, 'msg_code' => '', 'msg_des' => '', 'order' => '');
		if ($response['return_code'] == 'SUCCESS') {
			if ($response['result_code'] == 'SUCCESS' && $response['trade_state'] == 'SUCCESS') {			

				$order_info = get_field_by_where("shopping_orders", "*", "order_id = '{$order_no}'");

				if(empty($order_info)){
					show_message("/", "订单不存在");
				}
				if($this->logged_in==0){
					show_message("logreg", "请先登录");exit;
				}

				if($order_info['buyer_user_id']!=$this->user_data['id']){
					show_message("logreg", "不是你的订单");exit;
					exit;
				}

				//佣金
				$this->load->model("User_model");
	        	$user_commission = $this->User_model->get_user_commission($order_no);
	        	if(count($user_commission > 0)){
	        		foreach ($user_commission as $key => $value) {
	        			$this->db->where("user_id", $value['user_id']);
						$this->db->set("balance", "balance + {$value['commission']}", false);
						$this->db->set("commission_total", "commission_total + {$value['commission']}", false);
						$this->db->update("user_account");
						if($this->db->affected_rows() > 0){
							$this->db->where("id", $value['id']);
							$this->db->update("user_commission", array("status" => 1));
						}
	        		}
	        	}

				//扣网校视频课激活码
				if($order_info['order_type'] == 1){
					$time = time();
					$today_time = strtotime(date('Y-d-m'));
		        	$sql = "UPDATE {$this->db->dbprefix}o2o_school_video_user_codes SET status = 2, use_uid='{$order_info['buyer_user_id']}', use_time='{$time}', order_id='{$order_no}' WHERE school_id = '{$order_info['school_id']}' AND status = 1 AND expire_time >= '{$today_time}' ORDER BY id ASC LIMIT 1";
		        	$this->db->query($sql);
		        	if($this->db->affected_rows() > 0){
		        		$this->db->where("id", $order_info['school_id']);
						$this->db->set("item_num", "item_num - 1", false);
						$this->db->update("o2o_school");
		        	}
	        	}

				// if(1==1){
				if($order_info['order_status'] != 1 && $order_info['order_status'] != 2){
					$order_data['payment_method']  = 1;	//支付方式（1：微信支付，2：支付宝）
					$order_data['payment_status']  = 2; //支付状态：0未支付1支付中2支付成功3支付失败
					$order_data['payment_time']    = strtotime($response['time_end']); //付款时间
					$order_data['payment_on']      = $response['transaction_id']; //第三方支付交易号
					$order_data['payment_money_amount']     = $response['total_fee'] / 100; //实付金额
					$order_data['buyer_account']   = $response['openid']; //微信openid
					$order_data['order_detail']    = json_encode($response);
					$order_data['order_status']    = 1;	//订单确认成功，订单扣除激活码
					$this->db->update('shopping_orders', $order_data, array('order_id' => $order_no));

					$order_item = get_field_by_where("shopping_order_item", "*", "order_id='{$order_info['order_id']}'");
					if($order_item){
						if($order_info['order_type'] > 0 && $order_info['order_type'] < 4){
							$push_jihuo_code = false;
							if($order_info['order_type'] == 2 || $order_info['order_type'] == 3){
								$use_status = 1;
								$push_jihuo_code = true;
							}else{
								$course_info = get_field_by_where("course", "school_id", "id='{$order_item['course_id']}'");
								if($course_info['school_id'] > 0){
									$use_status = 1;
									$push_jihuo_code = true;
								}else{
									$use_status = $this->deduct_code($order_info, $order_item);
								}
							}
							if($push_jihuo_code){
								$time = time();
								$use_code_data['course_id'] = $order_item['course_id'];
								$use_code_data['course_type'] = $order_info['order_type'];
								$use_code_data['user_id'] = $order_info['buyer_user_id'];
								$use_code_data['code'] = 'schoo_course';
								$use_code_data['order_num'] = $order_info['order_num'];
								$use_code_data['school_id'] = $order_info['school_id'];
								$use_code_data['add_time'] = $time;
								$use_code_data['effective_time'] = $order_item['effective_time'];
								$this->db->insert("o2o_student_course", $use_code_data);
							}
						}elseif($order_info['order_type'] == 4){
							$subject_info = get_field_by_where("b_subject", "school_id", "id='{$order_item['course_id']}'");
							if($subject_info['school_id'] > 0){
								$use_status = 1;
								$push_jihuo_code = true;
							}else{
								$use_status = $this->deduct_code($order_info, $order_item);
							}
						}elseif($order_info['order_type'] == 5){
							$use_status = $this->deduct_code($order_info, $order_item);
						}

						if($use_status == 1){
							$this->db->update('shopping_orders', array('order_status' => 2), array('order_id' => $order_no));	//成功扣除激活码
							//插入有效期表的数据,先查询是否存在有效期数据,如果有就更新，没有就插入
							$time = time();
							$where = "data_type='{$order_info['order_type']}' AND data_id='{$order_item['course_id']}' AND uid='{$order_info['buyer_user_id']}'";
							$terms_info = get_field_by_where("o2o_student_item_terms", "*", $where);
							$terms_data['data_type'] = $order_info['order_type'];
							$terms_data['data_id'] = $order_item['course_id'];
							$terms_data['uid'] = $order_info['buyer_user_id'];
							$terms_data['lose_time'] = 3600 * 24 * $order_item['effective_time'] + $time;
							$terms_data['last_order_id'] = $order_no;
							if($terms_info){
								if($terms_info['lose_time'] > $time){
									$terms_data['lose_time'] = 3600 * 24 * $order_item['effective_time'] + $terms_info['lose_time'];
								}
								$this->db->where("id", $terms_info['id']);
								$this->db->update("o2o_student_item_terms", $terms_data);
							}else{
								$this->db->insert("o2o_student_item_terms", $terms_data);
							}
						}
					}
				}
				$result['status'] = 0;
				$result['order']  = $response;
				$this->smarty->assign("order", $order_info);
				$this->smarty->display("order/success.html");
			} else {
				$result['status']   = 2;
				$result['msg_code'] = !empty($response["err_code"]) ? $response["err_code"] : 0;
				$result['msg_des']  = !empty($response["err_code_des"]) ? $response["err_code_des"] : '';
				show_message("/", $result['msg_des']);
			}
			// exit(json_encode($result));
			
		} else {
			$result['status']   = 1;
			$result['msg_code'] = '微信服务器通信错误';
			$result['msg_des']  = $response["return_msg"];
			show_message("/", $result['msg_des']);
		}
	}

	function deduct_code($order_info, $order_item){
		$use_status = 0;
		if(!empty($order_info['order_id'])){
			$time = time();
			// $order_item = get_field_by_where("shopping_order_item", "*", "order_id='{$order_info['order_id']}'");
			if($order_item){
				$use_code_data = array();
				$where = "school_id = '{$order_info['school_id']}' AND status = 1 ";
				if($order_info['order_type'] > 0 && $order_info['order_type'] < 4){
					//课程订单
					$where .= "AND course_id = '{$order_item['course_id']}'";
					$code_info = get_field_by_where("o2o_school_system_video_course_codes", "*", $where . " ORDER BY id ASC");
					if($code_info){
						//插入课程激活码使用记录
						$use_code_data['course_id'] = $order_item['course_id'];
						$use_code_data['course_type'] = $order_info['order_type'];
						$use_code_data['user_id'] = $order_info['buyer_user_id'];
						$use_code_data['code'] = $code_info['code'];
						$use_code_data['order_num'] = $order_info['order_num'];
						$use_code_data['school_id'] = $order_info['school_id'];
						$use_code_data['add_time'] = $time;
						$use_code_data['effective_time'] = $order_item['effective_time'];
						$this->db->insert("o2o_student_course", $use_code_data);
						if($this->db->insert_id() > 0){
							//修改实训激活码的使用状态
							$code_update_data = array("status" => 2, "use_uid" => $use_code_data['user_id'], "use_time" => $time);
							$this->db->where("id", $code_info['id']);
							$this->db->update("o2o_school_system_video_course_codes", $code_update_data);
							$use_status = 1;
						}
					}
				}elseif($order_info['order_type'] ==  4){
					//题库订单、获取题库激活码
					$where .= "AND subject_id = '{$order_item['course_id']}'";
					$code_info = get_field_by_where("o2o_school_system_topic_codes", "*", $where . " ORDER BY id ASC");

					if($code_info){
						//插入题库激活码使用记录
						$use_code_data['subject_id'] = $order_item['course_id'];
						$use_code_data['uid'] = $order_info['buyer_user_id'];
						$use_code_data['code'] = $code_info['code'];
						$use_code_data['order_num'] = $order_info['order_num'];
						$use_code_data['school_id'] = $order_info['school_id'];
						$use_code_data['use_time'] = $time;
						$use_code_data['effective_time'] = $order_item['effective_time'];
						$this->db->insert("o2o_student_system_topics", $use_code_data);
						if($this->db->insert_id() > 0){
							//修改题库激活码的使用状态
							$code_update_data = array("status" => 2, "use_uid" => $use_code_data['uid'], "use_time" => $time);
							$this->db->where("id", $code_info['id']);
							$this->db->update("o2o_school_system_topic_codes", $code_update_data);
							$use_status = 1;
						}
					}
				}elseif($order_info['order_type'] == 5){
					//实训订单、获取题库激活码
					$where .= "AND sx_id = '{$order_item['course_id']}'";
					$code_info = get_field_by_where("o2o_school_system_shixun_codes", "*", $where . " ORDER BY id ASC");

					if($code_info){
						//插入实训激活码使用记录
						$use_code_data['sx_id'] = $order_item['course_id'];
						$use_code_data['uid'] = $order_info['buyer_user_id'];
						$use_code_data['code'] = $code_info['code'];
						$use_code_data['order_num'] = $order_info['order_num'];
						$use_code_data['school_id'] = $order_info['school_id'];
						$use_code_data['use_time'] = $time;
						$use_code_data['effective_time'] = $order_item['effective_time'];
						$this->db->insert("o2o_student_system_shixun", $use_code_data);
						if($this->db->insert_id() > 0){
							//修改实训激活码的使用状态
							$code_update_data = array("status" => 2, "use_uid" => $use_code_data['uid'], "use_time" => $time);
							$this->db->where("id", $code_info['id']);
							$this->db->update("o2o_school_system_shixun_codes", $code_update_data);
							$use_status = 1;
						}
					}
				}
			}
		}
		return $use_status;
	}

	function check_school_video_user_code(){
		$time = strtotime(date('Y-m-d'));
		$code_info = get_field_by_where("o2o_school_video_user_codes", "*", "school_id = '{$this->school_id}' AND status = 1 AND expire_time >= '{$time}'");
		if(!$code_info){
			show_message("/video", "该学校未开通视频课购买，请联系客服");
		}
	}
}
